package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author slstart
 * @create 2021-05-06 20:33
 */
public class MybatisUtils {
    private static InputStream is;
    private static SqlSessionFactory sqlSessionFactory ;

    static {
        try {
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
      * @return 返回一个需要手动提交事务的SqlSession对象
     * @throws IOException
     */
    public static SqlSession getSqlSession() throws IOException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

    /**
     * @return 返回一个自动提交事务的SqlSession对象
     * @throws IOException
     */
    public static SqlSession getSqlSession(boolean autoCommit) throws IOException {
        SqlSession sqlSession = sqlSessionFactory.openSession(autoCommit);
        return sqlSession;
    }

}
